const { apiKey, systemContent, maxTokens } = require('@/config/default').aliyun;

// 使用项目的模块别名系统
// 使用项目的模块别名系统
const validate = require('@/validate/index')
const tools = require('@/config/tools')
const OpenAI = require('openai')
const config = require('@/config/default')
const mcpConfig = require('@/config/mcp-servers')
const axios = require('axios')
const weatherController = require('@/controller/weather')
const { uploadToOSS } = require('@/config/oss')
const { safeJsonStringify } = require('@/utils/safeJson')
// MCP通信不再需要exec

class ChatController {
    constructor() {
        // 获取API Key和配置
        this.apiKey = config.aliyun.apiKey;
        this.systemContent = config.aliyun.systemContent;
        this.maxTokens = config.aliyun.maxTokens;
        // 开关控制是否使用真实MCP服务（true表示使用真实12306-mcp服务）
        this.useRealMcpService = true;

        // 初始化OpenAI客户端
        this.openai = new OpenAI({
            apiKey: this.apiKey,
            baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
        });
    }
    // 对话，流式输出
    async chatMessage(ctx) {
        // 提前保存this上下文
        const self = this;

        const { chatMessage } = ctx.request.body;
        // 校验参数
        await validate.arrayCheck(chatMessage, 'chatMessage字段不能为空', 'chatMessage');

        // 动态生成包含当前日期的系统提示
        const currentDate = new Date();
        const dateString = currentDate.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long', 
            day: 'numeric',
            weekday: 'long'
        });
        const isoDateString = currentDate.toISOString().split('T')[0];
        
        const dynamicSystemContent = this.systemContent + `

**当前真实日期：${dateString}（${isoDateString}）**
请基于这个真实日期来理解和回答所有与日期相关的问题。`;

        // 处理消息格式，确保图片消息能被正确处理
        const processedMessages = this.processMessages(chatMessage);
        
        // 检查是否包含图片，如果包含图片则使用支持视觉的模型
        const hasImage = this.hasImageContent(chatMessage);
        const modelName = hasImage ? "qwen-vl-max-latest" : "qwen-plus";
        
        console.log(`使用模型: ${modelName}, 包含图片: ${hasImage}`);
        
        // 处理系统消息格式
        const systemMessage = hasImage ? 
            { role: "system", content: [{ type: "text", text: dynamicSystemContent }] } :
            { role: "system", content: dynamicSystemContent };
        
        // 发送请求到OpenAI模型
        const completion = await this.openai.chat.completions.create({
            model: modelName,// 根据是否有图片选择模型
            messages: [
                systemMessage,
                ...processedMessages,
            ],
            stream: true,
            tools: hasImage ? undefined : tools, // 图片模式下不使用工具
            max_tokens: this.maxTokens, // 限制AI输出的最大token数量
        });

        // 设置响应头，支持流式传输
        ctx.set({
            'Content-Type': 'text/event-stream',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Methods': 'POST, OPTIONS'
        });

        // 发送初始连接确认
        ctx.res.write(`data: ${JSON.stringify({ type: 'connected' })}\n\n`);

        // 处理流式输出
        let toolCallInfo = null;
        let collectedToolArguments = null;
        let isHandlingToolCall = false;

        try {
            for await (const chunk of completion) {
                console.log(JSON.stringify(chunk));

                // 检查是否有文本内容
                if (chunk.choices && chunk.choices[0] && chunk.choices[0].delta && chunk.choices[0].delta.content) {
                    // 立即将文本片段发送给前端
                    const textChunk = chunk.choices[0].delta.content;
                    ctx.res.write(`data: ${JSON.stringify({
                        type: 'text',
                        content: textChunk
                    })}\n\n`);
                }

                // 检查是否有工具调用请求
                if (chunk.choices && chunk.choices[0] && chunk.choices[0].delta && chunk.choices[0].delta.tool_calls) {
                    const toolCall = chunk.choices[0].delta.tool_calls[0];

                    if (toolCall.function) {
                        // 记录工具名称（如果有）
                        if (toolCall.function.name) {
                            toolCallInfo = toolCall.function.name;
                        }

                        // 正确拼接增量参数
                        if (toolCall.function.arguments) {
                            if (!collectedToolArguments) {
                                collectedToolArguments = '';
                            }
                            collectedToolArguments += toolCall.function.arguments;
                            isHandlingToolCall = true;
                        }
                    }
                }

                // 检查是否有finish_reason，表明工具调用参数已完整或响应结束
                if (chunk.choices && chunk.choices[0] && chunk.choices[0].finish_reason) {
                    if (chunk.choices[0].finish_reason === 'tool_calls' && isHandlingToolCall) {
                        // 处理工具调用
                        try {
                            let toolResult;
                            console.log('工具调用名称:', toolCallInfo);
                            console.log('工具调用参数:', collectedToolArguments);

                            // 根据工具名称调用相应的处理函数
                            if (toolCallInfo === 'trainTicket') {
                                toolResult = await self.handleTrainTicketToolCall(collectedToolArguments);
                            } else if (toolCallInfo === 'weather') {
                                toolResult = await self.handleWeatherToolCall(collectedToolArguments);
                            } else {
                                toolResult = {
                                    success: false,
                                    message: `未知的工具调用: ${toolCallInfo}`
                                };
                            }

                            // 发送工具调用结果 - 使用安全的JSON序列化
                            ctx.res.write(`data: ${safeJsonStringify({
                                type: 'tool_result',
                                tool: toolCallInfo,
                                success: toolResult.success,
                                data: toolResult.data,
                                message: toolResult.message
                            })}\n\n`);
                        } catch (error) {
                            console.error('工具调用处理失败:', error);
                            ctx.res.write(`data: ${JSON.stringify({
                                type: 'tool_result',
                                tool: toolCallInfo || 'unknown',
                                success: false,
                                message: '工具调用失败: ' + error.message
                            })}\n\n`);
                        }

                        // 发送结束标志
                        ctx.res.write(`data: ${JSON.stringify({ type: 'end' })}\n\n`);
                        ctx.res.end();
                        return;
                    } else if (chunk.choices[0].finish_reason === 'stop') {
                        // 响应结束，发送结束标志
                        ctx.res.write(`data: ${JSON.stringify({ type: 'end' })}\n\n`);
                        ctx.res.end();
                        return;
                    }
                }
            }
        } catch (error) {
            console.error('流式响应处理错误:', error);
            if (!ctx.res.writableEnded) {
                ctx.res.write(`data: ${JSON.stringify({
                    type: 'error',
                    message: '响应处理出错: ' + (error.message || '未知错误')
                })}\n\n`);
                ctx.res.end();
            }
        } finally {
            // 确保响应已结束
            if (!ctx.res.writableEnded) {
                ctx.res.write(`data: ${JSON.stringify({ type: 'end' })}\n\n`);
                ctx.res.end();
            }
        }
    }

    // 处理火车票查询工具调用
    async handleTrainTicketToolCall(argumentsStr) {
        try {
            console.log('收到火车票查询请求，参数:', argumentsStr);

            // 解析参数
            let args;
            try {
                args = JSON.parse(argumentsStr);
            } catch (e) {
                console.log('JSON解析失败，尝试提取参数:', e.message);
                // 如果解析失败，尝试提取可能的参数
                args = this.extractTrainTicketParams(argumentsStr);
            }

            console.log('解析后的参数:', args);
            const { departure, destination, date } = args;

            // 验证参数
            if (!departure || !destination || !date) {
                return {
                    success: false,
                    message: '请提供完整的出发地、目的地和出行日期'
                };
            }

            // AI已经转换为标准格式，直接使用
            console.log(`📅 使用AI转换的日期: ${date}`);

            // 调用真实的12306-mcp服务
            const realTicketData = await this.queryRealTrainTickets(departure, destination, date);

            return realTicketData;
        } catch (error) {
            console.error('处理火车票查询失败:', error);
            return {
                success: false,
                message: '查询火车票失败，请稍后再试: ' + error.message
            };
        }
    }

    // 调用真实的12306-mcp服务查询火车票
    async queryRealTrainTickets(departure, destination, date) {
        try {
            console.log(`查询火车票: ${departure} -> ${destination}, 日期: ${date}`);

            // 如果未启用真实服务，直接返回模拟数据
            if (!this.useRealMcpService) {
                console.log('使用模拟数据模式，直接生成火车票信息');
                const enhancedMockData = this.generateEnhancedMockTicketData(departure, destination, date);
                return {
                    success: true,
                    data: enhancedMockData,
                    message: `成功查询到 ${enhancedMockData.length} 个车次（模拟数据）`
                };
            }

            // 尝试调用真实的12306-mcp服务
            const realTicketData = await this.call12306McpService(departure, destination, date);

            if (realTicketData && realTicketData.success) {
                return realTicketData;
            }

            // 如果真实服务失败，返回增强的模拟数据作为备选
            console.log('12306-mcp服务不可用，使用模拟数据');
            const enhancedMockData = this.generateEnhancedMockTicketData(departure, destination, date);

            return {
                success: true,
                data: enhancedMockData,
                message: `成功查询到 ${enhancedMockData.length} 个车次（模拟数据）`
            };

        } catch (error) {
            console.error('火车票查询失败:', error);
            return {
                success: false,
                message: '查询火车票失败，请稍后再试'
            };
        }
    }

    // 调用12306-mcp服务
    async call12306McpService(departure, destination, date) {
        try {
            console.log(`查询火车票: ${departure} -> ${destination}, 日期: ${date}`);

            // 获取12306-mcp服务配置
            const mcp12306Config = mcpConfig.mcpServers['12306-mcp'];
            if (!mcp12306Config) {
                throw new Error('未找到12306-mcp服务配置');
            }

            // 检查是否使用命令行模式
            if (mcp12306Config.command) {
                console.log(`使用命令行模式: ${mcp12306Config.command} ${mcp12306Config.args?.join(' ')}`);
                return await this.callCommandLineMcpService(departure, destination, date, mcp12306Config);
            }

            // 兼容旧的HTTP模式
            if (mcp12306Config.url) {
                return await this.callHttpMcpService(departure, destination, date, mcp12306Config);
            }

            throw new Error('12306-mcp服务配置无效');

        } catch (error) {
            console.error('调用12306-mcp服务失败:', error);

            // 返回详细的错误信息便于调试
            const errorMessage = `12306服务调用失败: ${error.message || '未知错误'}`;

            // 在服务不可用时仍然返回模拟数据
            console.log('12306-mcp服务不可用，使用模拟数据');
            const enhancedMockData = this.generateEnhancedMockTicketData(departure, destination, date);

            return {
                success: true, // 标记为成功，但使用模拟数据
                data: enhancedMockData,
                message: errorMessage + '，以下为模拟数据'
            };
        }
    }

    // 调用命令行模式的MCP服务
    async callCommandLineMcpService(departure, destination, date, config) {
        try {
            console.log(`查询车站代码: ${departure} -> ${destination}`);

            // 调用MCP服务获取车站代码
            const stationCodeResponse = await global.callMcpService('tools/call', {
                name: 'get-station-code-of-citys',
                arguments: {
                    citys: `${departure}|${destination}`
                }
            });

            console.log('车站代码响应:', JSON.stringify(stationCodeResponse));

            if (!stationCodeResponse || stationCodeResponse.error) {
                throw new Error(`获取车站代码失败: ${stationCodeResponse?.error?.message || '未知错误'}`);
            }

            // 解析车站代码
            const stationCodes = JSON.parse(stationCodeResponse.result.content[0].text);

            if (!stationCodes || !stationCodes[departure] || !stationCodes[destination]) {
                throw new Error('未找到对应的车站代码');
            }

            const fromStationCode = stationCodes[departure].station_code;
            const toStationCode = stationCodes[destination].station_code;

            console.log(`车站代码: ${departure}(${fromStationCode}) -> ${destination}(${toStationCode})`);

            console.log(`查询火车票: ${departure}(${fromStationCode}) -> ${destination}(${toStationCode}) 日期: ${date}`);

            // 调用MCP服务查询火车票
            const ticketsResponse = await global.callMcpService('tools/call', {
                name: 'get-tickets',
                arguments: {
                    date: date,
                    fromStation: fromStationCode,
                    toStation: toStationCode,
                    limitedNum: 10
                }
            });

            console.log('火车票响应:', JSON.stringify(ticketsResponse));

            if (!ticketsResponse || ticketsResponse.error) {
                throw new Error(`查询火车票失败: ${ticketsResponse?.error?.message || '未知错误'}`);
            }

            const ticketsData = ticketsResponse.result.content[0].text;

            // 解析12306-mcp返回的数据
            const parsedTickets = this.parse12306McpResponse(ticketsData, date);

            return {
                success: true,
                data: parsedTickets,
                message: `成功查询到 ${parsedTickets.length} 个车次`
            };

        } catch (error) {
            console.error('命令行MCP服务调用失败:', error);
            throw error;
        }
    }

    // 调用HTTP模式的MCP服务（兼容旧版本）
    async callHttpMcpService(departure, destination, date, config) {
        try {
            const mcpServiceUrl = config.url;
            console.log(`使用MCP服务URL: ${mcpServiceUrl}`);

            // 构建完整的JSON-RPC请求
            const queryStationCodesRequest = {
                jsonrpc: '2.0',
                id: Date.now(),
                method: 'get-station-code-of-citys',
                params: {
                    citys: `${departure}|${destination}`
                }
            };

            console.log('请求车站代码:', JSON.stringify(queryStationCodesRequest));

            // 发送请求获取车站代码
            // 确保URL不包含任何额外的格式字符
            const cleanUrl = mcpServiceUrl.replace(/[`']/g, '');

            let stationCodesResponse;
            try {
                stationCodesResponse = await axios.post(cleanUrl, queryStationCodesRequest, mcpConfig.defaultOptions);
                console.log('车站代码响应状态:', stationCodesResponse.status);
                console.log('车站代码响应:', JSON.stringify(stationCodesResponse.data));
            } catch (axiosError) {
                console.error('获取车站代码请求失败:', {
                    status: axiosError.response?.status,
                    statusText: axiosError.response?.statusText,
                    data: axiosError.response?.data,
                    config: axiosError.config
                });
                throw new Error(`获取车站代码请求失败: ${axiosError.message}`);
            }

            if (!stationCodesResponse.data || stationCodesResponse.data.error) {
                throw new Error(`获取车站代码失败: ${stationCodesResponse.data?.error?.message || '未知错误'}`);
            }

            // 解析车站代码响应
            const stationCodes = stationCodesResponse.data.result;

            if (!stationCodes || !stationCodes[departure] || !stationCodes[destination]) {
                throw new Error('未找到对应的车站代码');
            }

            const fromStationCode = stationCodes[departure].station_code;
            const toStationCode = stationCodes[destination].station_code;

            console.log(`车站代码: ${departure}(${fromStationCode}) -> ${destination}(${toStationCode})`);

            // 查询火车票
            const queryTicketsRequest = {
                jsonrpc: '2.0',
                id: Date.now(),
                method: 'get-tickets',
                params: {
                    date: date,
                    fromStation: fromStationCode,
                    toStation: toStationCode,
                    limitedNum: 10
                }
            };

            console.log('请求火车票:', JSON.stringify(queryTicketsRequest));

            // 发送请求查询火车票
            let ticketsResponse;
            try {
                ticketsResponse = await axios.post(cleanUrl, queryTicketsRequest, mcpConfig.defaultOptions);
                console.log('火车票响应状态:', ticketsResponse.status);
                console.log('火车票响应:', JSON.stringify(ticketsResponse.data));
            } catch (axiosError) {
                console.error('查询火车票请求失败:', {
                    status: axiosError.response?.status,
                    statusText: axiosError.response?.statusText,
                    data: axiosError.response?.data,
                    config: axiosError.config
                });
                throw new Error(`查询火车票请求失败: ${axiosError.message}`);
            }

            if (!ticketsResponse.data || ticketsResponse.data.error) {
                throw new Error(`查询火车票失败: ${ticketsResponse.data?.error?.message || '未知错误'}`);
            }

            const ticketsData = ticketsResponse.data.result;

            // 解析12306-mcp返回的数据
            const parsedTickets = this.parse12306McpResponse(ticketsData, date);

            return {
                success: true,
                data: parsedTickets,
                message: `成功查询到 ${parsedTickets.length} 个车次`
            };

        } catch (error) {
            console.error('HTTP MCP服务调用失败:', error);
            throw error;
        }
    }

    // 解析12306-mcp返回的数据
    parse12306McpResponse(ticketsData, date) {
        const tickets = [];

        // 检查是否为空数据
        if (!ticketsData || ticketsData === '没有查询到相关车次信息') {
            return tickets;
        }

        try {
            // 处理JSON格式的数据
            if (Array.isArray(ticketsData)) {
                // 如果是数组，直接处理每个车次
                ticketsData.forEach(ticketData => {
                    const parsedTicket = this.parseSingleTicketData(ticketData, date);
                    if (parsedTicket) {
                        tickets.push(parsedTicket);
                    }
                });
            } else if (typeof ticketsData === 'object' && ticketsData.tickets) {
                // 如果是对象且有tickets字段
                ticketsData.tickets.forEach(ticketData => {
                    const parsedTicket = this.parseSingleTicketData(ticketData, date);
                    if (parsedTicket) {
                        tickets.push(parsedTicket);
                    }
                });
            } else if (typeof ticketsData === 'string') {
                // 兼容旧的文本格式
                const lines = ticketsData.split('\n').filter(line => line.trim());

                for (let i = 1; i < lines.length; i++) { // 跳过标题行
                    const line = lines[i].trim();
                    if (!line || line.startsWith('-')) continue;

                    try {
                        // 解析车次信息行
                        const mainMatch = line.match(/^([A-Z]\d+)\(实际车次train_no:\s*([^)]+)\)\s+([^(]+)\(telecode:\s*([^)]+)\)\s*->\s*([^(]+)\(telecode:\s*([^)]+)\)\s+(\d{2}:\d{2})\s*->\s*(\d{2}:\d{2})\s+历时：(\d+:\d+)/);

                        if (mainMatch) {
                            const [, trainCode, trainNo, fromStation, fromCode, toStation, toCode, startTime, arriveTime, duration] = mainMatch;

                            const ticket = {
                                train_no: trainNo.trim(),
                                start_date: date, // 使用传入的日期参数
                                arrive_date: this.calculateArriveDate(date, startTime, duration),
                                start_train_code: trainCode.trim(),
                                start_time: startTime.trim(),
                                arrive_time: arriveTime.trim(),
                                lishi: duration.trim(),
                                from_station: fromStation.trim(),
                                to_station: toStation.trim(),
                                from_station_telecode: fromCode.trim(),
                                to_station_telecode: toCode.trim(),
                                prices: [],
                                dw_flag: []
                            };

                            // 解析价格信息（在后续行中）
                            let j = i + 1;
                            while (j < lines.length && lines[j].startsWith('-')) {
                                const priceLine = lines[j].trim();
                                const priceMatch = priceLine.match(/-\s*([^:]+):\s*(.+?)\s*(\d+)元/);
                                if (priceMatch) {
                                    const [, seatName, availability, price] = priceMatch;
                                    ticket.prices.push({
                                        seat_name: seatName.trim(),
                                        short: this.getSeatShort(seatName.trim()),
                                        seat_type_code: '',
                                        num: availability.trim(),
                                        price: parseInt(price),
                                        discount: null
                                    });
                                }
                                j++;
                            }

                            tickets.push(ticket);
                            i = j - 1; // 跳过已处理的价格行
                        }
                    } catch (error) {
                        console.error('解析车次信息失败:', error, line);
                    }
                }
            }
        } catch (error) {
            console.error('解析MCP响应数据失败:', error);
        }

        return tickets;
    }

    // 解析单个车次的JSON数据
    parseSingleTicketData(ticketData, date) {
        try {
            // 构建标准的车票对象格式
            const ticket = {
                train_no: ticketData.train_no || ticketData.trainNo || `240000${ticketData.trainCode || 'UNK'}0`,
                start_date: date, // 使用传入的日期参数
                arrive_date: this.calculateArriveDate(date, ticketData.startTime, ticketData.duration || '0:0'),
                start_train_code: ticketData.trainCode || ticketData.train_code || '未知',
                start_time: ticketData.startTime || ticketData.departure_time || '00:00',
                arrive_time: ticketData.arriveTime || ticketData.arrival_time || '00:00',
                lishi: ticketData.duration || ticketData.lishi || '0:00',
                from_station: ticketData.fromStation || ticketData.from_station || '未知',
                to_station: ticketData.toStation || ticketData.to_station || '未知',
                from_station_telecode: ticketData.fromCode || ticketData.from_station_telecode || 'XXX',
                to_station_telecode: ticketData.toCode || ticketData.to_station_telecode || 'XXX',
                prices: [],
                dw_flag: ticketData.features || ticketData.dw_flag || []
            };

            // 处理座位价格信息
            if (ticketData.prices && Array.isArray(ticketData.prices)) {
                ticketData.prices.forEach(priceInfo => {
                    ticket.prices.push({
                        seat_name: priceInfo.seat_name || priceInfo.name || '未知座位',
                        short: priceInfo.short || this.getSeatShort(priceInfo.seat_name || priceInfo.name || ''),
                        seat_type_code: priceInfo.seat_type_code || '',
                        num: priceInfo.num || priceInfo.availability || '有',
                        price: parseInt(priceInfo.price) || 0,
                        discount: priceInfo.discount || null
                    });
                });
            }

            // 如果没有价格信息，生成一些默认价格
            if (ticket.prices.length === 0) {
                const basePrice = Math.floor(Math.random() * 100) + 100; // 随机基础价格
                const trainType = ticket.start_train_code.charAt(0); // 获取车次类型首字母
                ticket.prices = this.generateDynamicPrices(basePrice, 0, trainType);
            }

            return ticket;
        } catch (error) {
            console.error('解析单个车次数据失败:', error, ticketData);
            return null;
        }
    }

    // 生成增强的模拟火车票数据（基于真实12306数据结构）
    generateEnhancedMockTicketData(departure, destination, date) {
        try {
            // 根据不同的出发地和目的地生成不同的车次
            const routeConfigs = this.getRouteConfig(departure, destination);
            const tickets = [];

            routeConfigs.forEach((config, index) => {
                // 生成基于时间的动态价格和余票
                const basePrice = config.basePrice;
                const priceVariation = Math.random() * 0.2 - 0.1; // ±10%的价格波动

                tickets.push({
                    train_no: config.trainNo,
                    start_date: date,
                    arrive_date: this.calculateArriveDate(date, config.startTime, config.duration),
                    start_train_code: config.trainCode,
                    start_time: config.startTime,
                    arrive_time: config.arriveTime,
                    lishi: config.duration,
                    from_station: departure,
                    to_station: destination,
                    from_station_telecode: config.fromCode,
                    to_station_telecode: config.toCode,
                    prices: this.generateDynamicPrices(basePrice, priceVariation, config.trainType),
                    dw_flag: config.features
                });
            });

            return tickets;
        } catch (error) {
            console.error('生成模拟火车票数据失败:', error);
            return [];
        }
    }

    // 获取路线配置
    getRouteConfig(departure, destination) {
        // 这里可以根据实际的城市对配置不同的车次
        const configs = [
            {
                trainCode: 'G1033',
                trainNo: '240000G10336',
                startTime: '09:00',
                arriveTime: '13:30',
                duration: '4:30',
                basePrice: 235,
                trainType: 'G',
                fromCode: 'NCG',
                toCode: 'SZQ',
                features: ['复兴号', '静音车厢']
            },
            {
                trainCode: 'D2012',
                trainNo: '240000D20123',
                startTime: '14:20',
                arriveTime: '19:45',
                duration: '5:25',
                basePrice: 185,
                trainType: 'D',
                fromCode: 'NCG',
                toCode: 'SZQ',
                features: ['智能动车组']
            },
            {
                trainCode: 'K507',
                trainNo: '240000K50789',
                startTime: '20:15',
                arriveTime: '08:30',
                duration: '12:15',
                basePrice: 85,
                trainType: 'K',
                fromCode: 'NCG',
                toCode: 'SZQ',
                features: []
            }
        ];

        // 根据出发地和目的地调整车次信息
        return configs.map(config => ({
            ...config,
            // 可以根据实际城市调整车次号和时间
            startTime: this.adjustTimeByRoute(config.startTime, departure, destination),
            arriveTime: this.adjustTimeByRoute(config.arriveTime, departure, destination),
            basePrice: this.adjustPriceByRoute(config.basePrice, departure, destination)
        }));
    }

    // 根据路线调整时间
    adjustTimeByRoute(time, departure, destination) {
        // 简单的时间调整逻辑，实际可以更复杂
        const timeVariation = Math.floor(Math.random() * 60) - 30; // ±30分钟
        const [hours, minutes] = time.split(':').map(Number);
        const totalMinutes = hours * 60 + minutes + timeVariation;
        const newHours = Math.floor(totalMinutes / 60) % 24;
        const newMinutes = totalMinutes % 60;
        return `${String(newHours).padStart(2, '0')}:${String(newMinutes).padStart(2, '0')}`;
    }

    // 根据路线调整价格
    adjustPriceByRoute(basePrice, departure, destination) {
        // 根据城市距离调整价格
        const distanceMultiplier = this.getDistanceMultiplier(departure, destination);
        return Math.round(basePrice * distanceMultiplier);
    }

    // 获取距离系数
    getDistanceMultiplier(departure, destination) {
        // 简化的距离计算，实际应该基于真实距离
        const cityDistances = {
            '南昌-深圳': 1.0,
            '北京-上海': 1.2,
            '广州-深圳': 0.3,
            '杭州-上海': 0.4
        };

        const key1 = `${departure}-${destination}`;
        const key2 = `${destination}-${departure}`;

        return cityDistances[key1] || cityDistances[key2] || 1.0;
    }

    // 计算到达日期
    calculateArriveDate(startDate, startTime, duration) {
        const [durationHours] = duration.split(':').map(Number);
        const [startHours] = startTime.split(':').map(Number);

        // 如果跨天
        if (startHours + durationHours >= 24) {
            const date = new Date(startDate);
            date.setDate(date.getDate() + 1);
            return date.toISOString().split('T')[0];
        }

        return startDate;
    }

    // 生成动态价格
    generateDynamicPrices(basePrice, priceVariation, trainType) {
        const prices = [];

        if (trainType === 'G' || trainType === 'D') {
            // 高铁/动车
            prices.push({
                seat_name: '二等座',
                short: 'ze',
                seat_type_code: 'O',
                num: this.generateTicketAvailability(),
                price: Math.round(basePrice * (1 + priceVariation)),
                discount: null
            });

            prices.push({
                seat_name: '一等座',
                short: 'zy',
                seat_type_code: 'M',
                num: this.generateTicketAvailability(),
                price: Math.round(basePrice * 1.6 * (1 + priceVariation)),
                discount: null
            });

            if (trainType === 'G') {
                prices.push({
                    seat_name: '商务座',
                    short: 'swz',
                    seat_type_code: '9',
                    num: this.generateTicketAvailability(),
                    price: Math.round(basePrice * 3.1 * (1 + priceVariation)),
                    discount: null
                });
            }
        } else {
            // 普通列车
            prices.push({
                seat_name: '硬座',
                short: 'yz',
                seat_type_code: '1',
                num: this.generateTicketAvailability(),
                price: Math.round(basePrice * (1 + priceVariation)),
                discount: null
            });

            prices.push({
                seat_name: '硬卧',
                short: 'yw',
                seat_type_code: '3',
                num: this.generateTicketAvailability(),
                price: Math.round(basePrice * 1.7 * (1 + priceVariation)),
                discount: null
            });

            prices.push({
                seat_name: '软卧',
                short: 'rw',
                seat_type_code: '4',
                num: this.generateTicketAvailability(),
                price: Math.round(basePrice * 2.6 * (1 + priceVariation)),
                discount: null
            });
        }

        return prices;
    }

    // 生成票量可用性
    generateTicketAvailability() {
        const availabilities = ['有', '充足', '1', '2', '3', '5', '8', '12', '无', '候补'];
        const weights = [30, 25, 5, 5, 8, 10, 8, 5, 3, 1]; // 权重

        let random = Math.random() * 100;
        for (let i = 0; i < weights.length; i++) {
            random -= weights[i];
            if (random <= 0) {
                return availabilities[i];
            }
        }
        return '有';
    }

    // 从字符串中提取火车票查询参数
    extractTrainTicketParams(argumentsStr) {
        const params = {};

        try {
            // 尝试更灵活的方式解析参数
            // 1. 处理可能的JSON片段
            let cleanStr = argumentsStr.trim();

            // 如果字符串以{开头但不以}结尾，尝试补全
            if (cleanStr.startsWith('{') && !cleanStr.endsWith('}')) {
                // 尝试查找最后一个逗号之前的位置
                const lastCommaIndex = cleanStr.lastIndexOf(',');
                if (lastCommaIndex > 0) {
                    cleanStr = cleanStr.substring(0, lastCommaIndex) + '}';
                } else {
                    cleanStr += '}';
                }
            }

            // 尝试使用简化的正则表达式提取参数
            // 提取出发地
            const departureMatch = cleanStr.match(/"departure"\s*:\s*"([^"]*)"/);
            if (departureMatch && departureMatch[1]) {
                params.departure = departureMatch[1];
            }

            // 提取目的地
            const destinationMatch = cleanStr.match(/"destination"\s*:\s*"([^"]*)"/);
            if (destinationMatch && destinationMatch[1]) {
                params.destination = destinationMatch[1];
            }

            // 提取日期
            const dateMatch = cleanStr.match(/"date"\s*:\s*"([^"]*)"/);
            if (dateMatch && dateMatch[1]) {
                params.date = dateMatch[1];
            }

        } catch (e) {
            console.error('解析参数失败:', e);
        }

        return params;
    }

    // 格式化日期
    formatDate(dateStr) {
        console.log('原始日期字符串:', dateStr);
        
        // 获取当前日期
        const today = new Date();
        const currentYear = today.getFullYear();
        const currentMonth = today.getMonth();
        const currentDate = today.getDate();
        
        // 处理相对日期
        if (dateStr.includes('今天') || dateStr.includes('今日')) {
            const result = this.formatDateToString(today);
            console.log('今天日期转换:', result);
            return result;
        }
        
        if (dateStr.includes('明天') || dateStr.includes('明日')) {
            const tomorrow = new Date(currentYear, currentMonth, currentDate + 1);
            const result = this.formatDateToString(tomorrow);
            console.log('明天日期转换:', result);
            return result;
        }
        
        if (dateStr.includes('后天')) {
            const dayAfterTomorrow = new Date(currentYear, currentMonth, currentDate + 2);
            const result = this.formatDateToString(dayAfterTomorrow);
            console.log('后天日期转换:', result);
            return result;
        }
        
        if (dateStr.includes('大后天')) {
            const threeDaysLater = new Date(currentYear, currentMonth, currentDate + 3);
            const result = this.formatDateToString(threeDaysLater);
            console.log('大后天日期转换:', result);
            return result;
        }
        
        // 处理星期几
        const weekdayMatch = dateStr.match(/(星期|周)([一二三四五六日天])/);
        if (weekdayMatch) {
            const weekdayMap = {
                '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '日': 0, '天': 0
            };
            const targetWeekday = weekdayMap[weekdayMatch[2]];
            const currentWeekday = today.getDay();
            
            let daysToAdd = targetWeekday - currentWeekday;
            if (daysToAdd <= 0) {
                daysToAdd += 7; // 下周的这一天
            }
            
            const targetDate = new Date(currentYear, currentMonth, currentDate + daysToAdd);
            const result = this.formatDateToString(targetDate);
            console.log(`${weekdayMatch[0]}日期转换:`, result);
            return result;
        }
        
        // 处理下周星期几
        const nextWeekMatch = dateStr.match(/下(个)?[周星期]+(星期|周)([一二三四五六日天])/);
        if (nextWeekMatch) {
            const weekdayMap = {
                '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '日': 0, '天': 0
            };
            const targetWeekday = weekdayMap[nextWeekMatch[3]];
            const currentWeekday = today.getDay();
            
            let daysToAdd = targetWeekday - currentWeekday + 7; // 下周
            if (daysToAdd <= 7) {
                daysToAdd += 7; // 确保是下周
            }
            
            const targetDate = new Date(currentYear, currentMonth, currentDate + daysToAdd);
            const result = this.formatDateToString(targetDate);
            console.log(`下周${nextWeekMatch[2]}${nextWeekMatch[3]}日期转换:`, result);
            return result;
        }
        
        // 处理数字天数后
        const daysLaterMatch = dateStr.match(/(\d+)天后/);
        if (daysLaterMatch) {
            const daysToAdd = parseInt(daysLaterMatch[1]);
            const targetDate = new Date(currentYear, currentMonth, currentDate + daysToAdd);
            const result = this.formatDateToString(targetDate);
            console.log(`${daysToAdd}天后日期转换:`, result);
            return result;
        }
        
        // 处理标准日期格式
        if (dateStr.match(/\d{4}-\d{2}-\d{2}/)) {
            console.log('标准日期格式，无需转换:', dateStr);
            return dateStr;
        }
        
        if (dateStr.match(/\d{4}年\d{1,2}月\d{1,2}日/)) {
            // 转换 2025年9月22日 格式为 2025-09-22
            const result = dateStr.replace(/年/g, '-').replace(/月/g, '-').replace(/日/g, '');
            // 补齐月份和日期的零
            const parts = result.split('-');
            if (parts.length === 3) {
                const formattedResult = `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`;
                console.log('中文日期格式转换:', formattedResult);
                return formattedResult;
            }
        }
        
        // 处理月日格式（如：9月24日）
        const monthDayMatch = dateStr.match(/(\d{1,2})月(\d{1,2})日/);
        if (monthDayMatch) {
            const month = monthDayMatch[1].padStart(2, '0');
            const day = monthDayMatch[2].padStart(2, '0');
            const result = `${currentYear}-${month}-${day}`;
            console.log('月日格式转换:', result);
            return result;
        }
        
        console.log('无法识别的日期格式，返回原始字符串:', dateStr);
        return dateStr;
    }
    
    // 将Date对象格式化为YYYY-MM-DD字符串
    formatDateToString(date) {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 获取座位简称
    getSeatShort(seatName) {
        const seatMap = {
            '二等座': 'ze',
            '一等座': 'zy',
            '商务座': 'swz',
            '硬座': 'yz',
            '硬卧': 'yw',
            '软卧': 'rw'
        };
        return seatMap[seatName] || '';
    }

    // 处理天气查询工具调用
    async handleWeatherToolCall(argumentsStr) {
        try {
            console.log('收到天气查询请求，参数:', argumentsStr);

            // 解析参数
            let args;
            try {
                args = JSON.parse(argumentsStr);
            } catch (e) {
                console.log('JSON解析失败，尝试提取参数:', e.message);
                // 如果解析失败，尝试提取可能的参数
                args = this.extractWeatherParams(argumentsStr);
            }

            console.log('解析后的参数:', args);
            const { city } = args;

            // 验证参数
            if (!city) {
                return {
                    success: false,
                    message: '请提供要查询天气的城市名称'
                };
            }

            // 调用天气控制器查询天气
            const weatherResult = await weatherController.getWeatherInfo(city);

            if (weatherResult.success) {
                // 格式化天气信息为用户友好的文本
                const weatherText = weatherController.formatWeatherText(weatherResult.data);
                const weatherAdvice = weatherController.generateWeatherAdvice(weatherResult.data);

                return {
                    success: true,
                    data: {
                        ...weatherResult.data,
                        formattedText: weatherText + weatherAdvice
                    },
                    message: weatherResult.message
                };
            } else {
                return weatherResult;
            }

        } catch (error) {
            console.error('处理天气查询失败:', error);
            return {
                success: false,
                message: '天气查询失败，请稍后再试: ' + error.message
            };
        }
    }

    // 从字符串中提取天气查询参数
    extractWeatherParams(argumentsStr) {
        const params = {};

        try {
            // 尝试更灵活的方式解析参数
            let cleanStr = argumentsStr.trim();

            // 如果字符串以{开头但不以}结尾，尝试补全
            if (cleanStr.startsWith('{') && !cleanStr.endsWith('}')) {
                // 尝试查找最后一个逗号之前的位置
                const lastCommaIndex = cleanStr.lastIndexOf(',');
                if (lastCommaIndex > 0) {
                    cleanStr = cleanStr.substring(0, lastCommaIndex) + '}';
                } else {
                    cleanStr += '}';
                }
            }

            // 尝试使用简化的正则表达式提取参数
            // 提取城市名
            const cityMatch = cleanStr.match(/"city"\s*:\s*"([^"]*)"/);
            if (cityMatch && cityMatch[1]) {
                params.city = cityMatch[1];
            }

        } catch (e) {
            console.error('解析天气参数失败:', e);
        }

        return params;
    }

    // 处理消息格式，确保兼容不同的输入格式
    processMessages(messages) {
        return messages.map(message => {
            // 如果消息内容是数组（包含文本和图片）
            if (Array.isArray(message.content)) {
                // 检查是否所有内容都是文本类型
                const allText = message.content.every(item => item.type === 'text');
                if (allText) {
                    // 如果都是文本，合并为单个字符串
                    return {
                        ...message,
                        content: message.content.map(item => item.text).join(' ')
                    };
                }
                // 如果包含图片，保持原格式
                return message;
            }
            // 如果是字符串内容，保持原样
            return message;
        });
    }

    // 检查消息中是否包含图片内容
    hasImageContent(messages) {
        return messages.some(message => {
            if (Array.isArray(message.content)) {
                return message.content.some(item => 
                    item.type === 'image_url' || 
                    item.type === 'image'
                );
            }
            return false;
        });
    }
}

module.exports = new ChatController();